package com.tanger.permission.permission.web;

import com.tanger.common.exception.AbstractController;
import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.StringUtil;
import com.tanger.permission.entity.role.EntityUserRole;
import com.tanger.permission.entity.vo.UserRoleVo;
import com.tanger.permission.permission.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 控制层
 */
@RestController
@RequestMapping("/tanger/bts/user-role")
@Api(value = "用户角色",tags="用户角色")
public class UserRoleController extends AbstractController {

	@Autowired
	private UserRoleService userRoleService;

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@ApiImplicitParam(name = "userId", value = "主键ID", required = true, dataType = "Long")
	@ApiOperation(value = "用户角色详情")
	@GetMapping("/{userId}")
	public ActionResult<UserRoleVo> getInfo(@PathVariable Long userId) {
		try {
			if (StringUtil.isNull(userId)) return ActionResult.buildResultError("参数缺失");
			return ActionResult.buildResultSuccess(userRoleService.findAll(userId));
		} catch (Exception e) {
			return ActionResult.buildResultError(e.getMessage());
		}
	}


	@ApiOperation(value = "保存用户角色")
	@PostMapping(value = "/saveUserRole")
	public ActionResult saveUserRole(@RequestBody List<EntityUserRole> userRoles) {
		try {
			if (CollectionUtils.isEmpty(userRoles)) return ActionResult.buildResultSuccess();
			long count = userRoles.stream().filter(x -> StringUtil.isNull(x.getUserId()) || StringUtil.isNull(x.getRoleId())).count();
			if (count > 0L) return ActionResult.buildResultError("参数缺失");
			return userRoleService.saveUserRole(userRoles);
		} catch (Exception e) {
			return ActionResult.buildResultError(e.getMessage());
		}
	}

	@ApiImplicitParam(name = "ids", value = "主键ID数组", required = true, dataType = "List")
	@ApiOperation(value = "用户角色删除")
	@PostMapping(value = "/deleteUserRole")
	public ActionResult deleteUserRole(@RequestBody Long[] ids) {
		try {
			if (CollectionUtils.isEmpty(Arrays.asList(ids))) return  ActionResult.buildResultError("参数缺失");
			return userRoleService.deleteUserRole(ids);
		} catch (Exception e) {
			return ActionResult.buildResultError(e.getMessage());
		}
	}
}